<?php


namespace app\index\controller;


use app\index\model\User;
use think\Controller;
use think\Request;
use think\response\Json;
use think\Session;

class Login extends Controller
{
    /**
     * @var \app\index\model\Login login模型对象
     */
    protected $login;
    protected $request;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=$request;
        $this->login=new \app\index\model\Login();
    }

    /**
     * doLogin
     * 登录
     * @url /dologin
     * @method POST
     * @request string name 用户名
     * @request string password 密码
     * @return Json
     * @author Asira
     * @date 2021/2/3
     */
    public function doLogin(): Json
    {
        $username=input('post.name');
        $password=input('post.password');
        $password=md5($password);
//        return json(['code'=>1,'msg'=>$password],200);
        //检验登录
        $result=$this->login->doLogin($username,$password);
        if($result['status']===false){
            return json(['code'=>1,'msg'=>$result['msg']],200);
        }
        $user_data=$result['data'];

        //生成token
        $microtime=microtime();
        $token=hash('sha256',$user_data['user_name'].$user_data['role'].$microtime.$user_data['user_name']);
        $last_token_time=date('Y-m-d H:i:s');
        //设置session数据
        Session::set('Login_user',[
            'name'=>$user_data['user_name'],
            'id'=>$user_data['id'],
            'role'=>$user_data['role'],
            'role_detail_id'=>$user_data['role_detail_id'],
            'group_id'=>$user_data['group_id'],
            'token'=>$token,
        ]);
        //生成可访问的菜单权限
//        $menu=implode(',',$result['menu']);
        //写入登录信息json文件
        try {
            self::writeToken($user_data, $microtime, $token,$last_token_time);
        }catch(\Exception $e){
            trace('Login Error '.$e,'error');
        }
        return json(['code'=>0,
            'msg'=>'登录成功',
            'id'=>$user_data['id'],
            'url'=>'/home',
            'role'=>$user_data['role'],
            'role_detail'=>$user_data['role_detail_id'],
            'menu'=>$result['menu'],
            'action_role'=>$result['action'],
            'user_name'=>$user_data['user_name'],
            'group_id'=>$user_data['group_id'],
            'group_name'=>$user_data['group_name'],
            'role_name'=>$user_data['role_name'],
            'token'=>$token],200);
    }

    public static function writeToken($user_data,$microtime,$token,$last_token_time){
        $dir=APP_PATH.'websocket'.DIRECTORY_SEPARATOR.'json'.DIRECTORY_SEPARATOR.'user'.$user_data['id'].'.json';
        // DIRECTORY_SEPARATOR ’/‘
        if(is_file($dir)){
            //存在已只读方式打开
            $files=fopen($dir, 'rb+');
        }else{
            //不存在以写入方式打开
            $files=fopen($dir, 'wb+');
        }
        $file_size=filesize($dir);
        //判断文件是否有内容
        if($file_size>0){
            $json=fread($files,filesize($dir));
            $data=json_decode($json,true);
            //判断内容是否正确
            if($data){
                $data['user_name']=$user_data['user_name'];
                $data['user_id']=$user_data['id'];
                $data['user_role']=$user_data['role'];
                //移除已经过期的token
                foreach ($data['last_token_time'] as $key=>$value){
                    if((time()-strtotime($value))>3600*24){
                        unset($data['user_token'][$key], $data['user_ip'][$key], $data['user_login_time'][$key],$data['last_token_time'][$key]);
                    }
                }
                $data['user_token']=array_values($data['user_token']);
                $data['user_ip']=array_values($data['user_ip']);
                $data['user_login_time']=array_values($data['user_login_time']);
                $data['last_token_time']=array_values($data['last_token_time']);
                //同时存在的token最多为5
                if(count($data['user_token'])>5){
                    unset($data['user_token'][0], $data['user_ip'][0], $data['user_login_time'][0],$data['last_token_time'][0]);
                }
                $data['last_token_time'][]=$last_token_time;
                $data['user_token'][]=$token;
                $data['user_login_time'][]=$microtime;
                $data['user_ip'][]=Request::instance()->ip();
                fclose($files);
                //重新写入方式打开文件
                $files=fopen($dir, 'wb+');
                fwrite($files,json_encode($data));
                fclose($files);
                return;
            }
        }
        $write_data=[
            'user_name'=>$user_data['user_name'],
            'user_id'=>$user_data['id'],
            'user_role'=>$user_data['role'],
            'user_token'=>[$token],
            'last_token_time'=>[$last_token_time],
            'user_login_time'=>[$microtime],
            'user_ip'=>[Request::instance()->ip()],
        ];
        fwrite($files,json_encode($write_data));
        fclose($files);
    }
}